package com.ff.javamonkey.sqlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class SingletonDb {
	// Debugging
	private static final String TAG = "SingletonDb";
	
	private static SingletonDb instance;
	private SQLiteDatabase mDb;
	
	private OpenDatabaseHelper mDbHelper;
	
	private Context mContext;
	
	private static String dbName;
	
	private ACRLDbAdapter mACRLDbAdapter;
	
	public SingletonDb(Context ctx) {
		this.mContext = ctx;
		Log.d(TAG, "Creating new singleton db instance");
	}
	
	public static SingletonDb getDb(Context ctx, String name) {
		dbName = name;
		if (instance == null) {
			instance = new SingletonDb(ctx);
		}
		if (!instance.isOpen()) {
			instance.open();
		}
		return instance;
	}

	public SingletonDb open() {
		if (mDbHelper == null) {
			mDbHelper = new OpenDatabaseHelper(mContext, dbName);
		}
		if (mACRLDbAdapter == null) {
			mACRLDbAdapter = new ACRLDbAdapter(mDbHelper);
			mACRLDbAdapter.open();
		}
		return this;
	}
	
	public static void close() {
		if (instance != null && instance.isOpen()) {
			Log.i(TAG, "Are we getting a call? " + dbName);
			instance.closeInstance();
		}
		instance = null;
	}
	
	public void closeInstance() {
        mDbHelper.close();
        // just for precaution, not really sure at this point 
        //whether the following is necessary or not
        if (mDb.isOpen()) {
        	mDb.close();
        }
	}
	
	public boolean isOpen() {
		return mDb != null && mDb.isOpen();
	}

	public OpenDatabaseHelper getDbHelper() {
		return mDbHelper;
	}
	
	public ACRLDbAdapter getACRLDbAdapter() {
		return mACRLDbAdapter;
	}
}
